package com.dgut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dgut.mapper.AccountMapper;
import com.dgut.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class JwtUserDetailServiceImpl implements UserDetailsService {
    @Resource
    private AccountMapper accountMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Account account = this.accountMapper.selectOne(wrapper);
        if(account == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> authLists = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_"+account.getRole());
        //查询账号是否被锁
        Boolean isNonLocked = account.getIsLocked() == 0 ? true : false;
        User user = new User(account.getUsername(),account.getPassword(),true,true,true,isNonLocked,authLists);

        return user;
    }
}
